#include "head_c.h"

void* start_gets(void* p)
{
    portocol_t* portocol = (portocol_t*)p;
    char ip[20] = {0};
    getparameter("ip", ip);
    char port[10] = {0};
    getparameter("port", port);

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    
    struct sockaddr_in sockaddr;
    sockaddr.sin_family=AF_INET;
    sockaddr.sin_port=htons(atoi(port));
    sockaddr.sin_addr.s_addr=inet_addr(ip);

    connect(socket_fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
    send(socket_fd, portocol, sizeof(portocol_t), MSG_NOSIGNAL);
    send(socket_fd, portocol, sizeof(portocol_t), MSG_NOSIGNAL);
    download(socket_fd);
    close(socket_fd);
}

int do_gets(const portocol_t* portocol)
{
    pthread_t tid;
    portocol_t port_gets;
    memcpy(&port_gets, portocol, sizeof(portocol_t));
    LOG_WRITE(LOG_ERROR, "%s, %d", port_gets.arg, port_gets.cmd);
    pthread_create(&tid, NULL, start_gets, (void*)&port_gets);
    return 0;
}



int download(int socket_fd)
{
    int file_name_len = 0;
    char file_name[60] = {0};
    size_t file_size = 0;
    char ret[10] = {0};

    LOG_WRITE(LOG_ERROR, "%s\n", ret);
    recv(socket_fd, ret, 1, MSG_WAITALL);
    LOG_WRITE(LOG_ERROR, "%s\n", ret);
    if (strcmp(ret, "1") == 0)
    {
        printf("无此文件\n");
        return -1;
    }
    recv(socket_fd, &file_name_len, sizeof(int), MSG_WAITALL);
    LOG_WRITE(LOG_ERROR,"文件名长度：%d", file_name_len);
    recv(socket_fd, file_name, file_name_len, MSG_WAITALL);
    LOG_WRITE(LOG_ERROR,"文件名：%s", file_name);
    recv(socket_fd, &file_size, sizeof(size_t), MSG_WAITALL);
    LOG_WRITE(LOG_ERROR,"文件长度：%ld", file_size);

    LOG_WRITE(LOG_ERROR, "%s\n", file_name);
    int file_fd = open(file_name, O_RDWR | O_CREAT, 0666);
    ftruncate(file_fd, file_size);
    char* p = (char*)mmap(NULL, file_size, PROT_READ | PROT_WRITE, MAP_SHARED, file_fd, 0);
    int ret_size = recv(socket_fd, p, file_size, MSG_WAITALL);
    munmap(p, file_size);
    ftruncate(file_fd, ret_size);
    LOG_WRITE(LOG_ERROR,"接收到的文件字节数：%d", ret_size);
    printf("文件传输完成\n");

    close(file_fd);

    return 0;
}
